package medium;

import java.util.Arrays;

/**
 * @author cmqzyd0700@163.com
 * @version 1.0
 * @since 2021/7/29 20:06
 */
public class No16_最接近的三数之和 {
    public static void main(String[] args) {
        Solution16 solution16 = new Solution16();
        int[] nums = new int[]{2, 2, 3, -4, 7, -9};
        int i = solution16.threeSumClosest(nums, -3);
        
    }
}

class Solution16 {
    public int threeSumClosest(int[] nums, int target) {
        //排序
        Arrays.sort(nums);
        int length = nums.length;
        //最小距离,0肯定最小,所以不能是0,这里有问题
        int juli = Integer.MAX_VALUE;

        //最接近target的值
        int res = 0;
        for (int big = 0; big < length; big++) {
            int red = big + 1;
            int green = length - 1;
            //big相同处理
            if (big > 0 && nums[big] == nums[big - 1]) {
                continue;
            }
            //处理
            while (red < green) {
                //跳过问题
                if (red > big + 1 && nums[red] == nums[red - 1]) {
                    red++;
                    continue;
                }
                if (green < length - 1 && nums[green] == nums[green + 1]) {
                    green--;
                    continue;
                }
                //可以处理
                int a = nums[red];
                int b = nums[green];
                int c = nums[big];
                //获取目标值
                int check = target - c;
                if (a + b > check) {
                    //要接近目标值咋办?green--!!
                    green--;
                    //获取当前最小的接近距离
                    if (a + b - check < juli) {
                        juli = a + b - check;
                        res = a + b + c;
                    }
                } else if (a + b < check) {
                    //要接近目标值咋办? red++!!!
                    red++;
                    if (check - a - b < juli) {
                        juli = check - a - b;
                        res = a + b + c;
                    }
                } else {
                    //距离为0!!直接返回
                    //red++;
                    //green--; //不用! 已经return了
                    return a + b + c;
                } 
                
            }
        }
        return res;
    }
}







